<?php
namespace app\admin\model;

use think\facade\Request;

class Login
{
    /**
     * 登录操作
     * @param string $username 账号
     * @param string $password 密码
     * @return array 登录结果
     */
    public function login($username, $password){
        $administrator = new Administrator();
        //获取管理员信息
        $where['username'] = $username;
        $result = $administrator->where($where)->find();
        //判断登录
        $ret = ['status_code' => 1, 'status_info' => '未知错误！'];
        if (!$result || $result['status'] != 1){
            $ret['status_info'] = '该账号不存在或已冻结！';
            return $ret;
        }
        if ($result['password'] != $password){
            $ret['status_info'] = '密码错误！';
            return $ret;
        }
        //登录成功
        session('uid', $result['id']);
        session('username', $result['username']);
        session('is_root', is_root($result['id']));
        session('login_number', $result['login_number']+1);
        session('last_login_ip', long2ip($result['last_login_ip']));
        session('last_login_time', date('Y-m-d H:i:s', $result['last_login_time']));
        //更新登录信息
        $data['login_number'] = session('login_number');
        $data['last_login_ip'] = Request::ip(1, true);
        $data['last_login_time'] = time();
        $administrator->save($data, $where);
        //返回登录结果
        return $ret = ['status_code' => 0, 'status_info' => '登录成功。'];
    }

    /**
     * 注销操作
     * @return mixed
     */
    public function logout(){
        return session(null);
    }

}
